<template>
  <view class="message-container">
    <!-- 消息组件 -->
    <view 
      v-for="(message, index) in messages" 
      :key="index"
      :class="['message', message.type]"
      :style="{ top: 80 + index * 60 + 'rpx' }"
    >
      <text class="message-content">{{ message.content }}</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

interface Message {
  id: number;
  content: string;
  type: 'success' | 'error' | 'warning' | 'info';
  duration: number;
}

const messages = ref<Message[]>([]);

let messageId = 0;

// 添加消息
const addMessage = (options: { content: string; type: 'success' | 'error' | 'warning' | 'info'; duration?: number }) => {
  const id = messageId++;
  const message: Message = {
    id,
    content: options.content,
    type: options.type,
    duration: options.duration || 3000
  };

  messages.value.push(message);

  // 自动移除消息
  setTimeout(() => {
    removeMessage(id);
  }, message.duration);
};

// 移除消息
const removeMessage = (id: number) => {
  const index = messages.value.findIndex(msg => msg.id === id);
  if (index !== -1) {
    messages.value.splice(index, 1);
  }
};

// 暴露方法给父组件
defineExpose({
  addMessage
});
</script>

<style scoped>
.message-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 9999;
  pointer-events: none;
}

.message {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  padding: 20rpx 30rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  min-width: 300rpx;
  justify-content: center;
  animation: slideInDown 0.3s ease;
}

.message.success {
  background-color: #67C23A;
}

.message.error {
  background-color: #F56C6C;
}

.message.warning {
  background-color: #E6A23C;
}

.message.info {
  background-color: #409EFF;
}

.message-content {
  text-align: center;
}

@keyframes slideInDown {
  from {
    opacity: 0;
    transform: translate(-50%, -20rpx);
  }
  to {
    opacity: 1;
    transform: translate(-50%, 0);
  }
}
</style>